package com.lcf.framework.utils;

import com.lcf.framework.exception.SysException;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * 图片工具类
 *
 * @author lcf
 */
public class ImageUtils {
    /**
     * 图片压缩
     */
    public static InputStream compressImg(MultipartFile file) throws Exception {
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new SysException("图片过大");
        }
        return compressImg(file.getInputStream());
    }

    /**
     * 压缩
     */
    public static InputStream compressImg(InputStream inputStream) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            Thumbnails.of(inputStream)
                    //图片大小（长宽）压缩比例 从0-1，1表示原图
                    .scale(1f)
                    //图片质量压缩比例 从0-1，越接近1质量越好
                    .outputQuality(0.5f)
                    .toOutputStream(bos);
            return new ByteArrayInputStream(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * base64字符串转化成图片
     */
    public static InputStream base64ToImg(String imgData) throws IOException {
        // 对字节数组字符串进行Base64解码并生成图片
        if (imgData == null) {
            return null;
        }

        Base64.Decoder decoder = Base64.getDecoder();
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            // Base64解码
            byte[] b = decoder.decode(imgData);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += (byte) 256;
                }
            }
            out.write(b);
            byte[] arr = out.toByteArray();
            return new ByteArrayInputStream(arr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }

        return null;
    }
}
